#include "StdAfx.h"
#include "db_manager.h"

/*
author: Jackong
*/

db_manager::db_manager()
	:qry_mutex_()
{
	mysql_init(&mysql_);
	connect();
}

bool db_manager::connect()
{
	if (!mysql_real_connect(&mysql_, "172.22.71.125", "jack", "69318520", "tribal", 0, NULL, 0))
	{
		cerr<<"connect db faild:"<<mysql_error(&mysql_)<<endl;
		return false;
	}
	cout<<"connect db successful"<<endl;
	return true;
}

bool db_manager::query(const char* cmd, MYSQL_RES* res)
{
	boost::mutex::scoped_lock lock(qry_mutex_);
	return query_non_lock(cmd, res);
}
bool db_manager::query_non_lock(const char* cmd, MYSQL_RES* res)
{
	//LOG_DEBUG("query cmd: ", cmd);
	if (mysql_real_query(&mysql_, cmd, strlen(cmd)))
	{
		LOG_ERR("query faild: ", mysql_error(&mysql_));
		return false;
	}
	if (res)
	{
		*res = *mysql_store_result(&mysql_);
	}
	return true;
}
bool db_manager::prepare_manual_commit()
{
	qry_mutex_.lock();
	return set_autocommit(false);
}
bool db_manager::set_autocommit(bool at)
{
	if (mysql_autocommit(&mysql_, at))
	{
		LOG_ERR("set auto commit faild:", mysql_error(&mysql_));
		return false;
	}
	return true;
}
bool db_manager::commit()
{
	my_bool is_error = mysql_commit(&mysql_);
	set_autocommit(true);
	qry_mutex_.unlock();
	if (is_error)
	{
		LOG_ERR("commit faild:", mysql_error(&mysql_));
		return false;
	}
	return true;
}

void db_manager::escape(string& val)
{
	char* cval = new char[2 * val.size() + 1];
	mysql_real_escape_string(&mysql_, cval, val.c_str(), val.size());
	val.clear();
	val.append(cval);
	delete [] cval;
}